<?php
/*
 * Created on 2012-6-29
 *
 * 从Excel导入视频数据
 *
 */

$nns_db_vod_dir = dirname ( dirname ( __FILE__ ) );
require_once $nns_db_vod_dir . DIRECTORY_SEPARATOR . "nns_common" . DIRECTORY_SEPARATOR . "nns_db_class.php";
require_once $nns_db_vod_dir . DIRECTORY_SEPARATOR . "nns_common" . DIRECTORY_SEPARATOR . "nns_db_guid_class.php";
require_once $nncms_config_path. "nn_cms_manager/controls/nncms_controls_pinyin_class.php";
require_once $nns_db_vod_dir . DIRECTORY_SEPARATOR.'nns_debug_log'.DIRECTORY_SEPARATOR.'nns_debug_log_class.php';
class nns_db_vod_import_class {
	private $conn;
	private $db_obj;
    private $log;
	public function __construct() {
		$this->db_obj = new nns_db_class ( g_db_host, g_db_username, g_db_password, g_db_name );
		$this->conn = $this->db_obj->nns_db_connect ();
		$this->log =  new nns_debug_log_class();
        $this->log->setlogpath('vod_import_excel');
	}
	public function save_vod ($dataset,$nns_org_type,$nns_org_id,$depot_id) {

		$sql = "insert into nns_vod (" .
				"nns_id,nns_depot_id," .
				"nns_category_id," .
				"nns_view_type," .
				"nns_state," .
				"nns_pinyin," .
				"nns_tag," .
				"nns_point," .
				"nns_org_type," .
				"nns_org_id," .
				"nns_name,nns_alias_name," .
				"nns_eng_name," .
				"nns_area," .
				"nns_language," .
				"nns_text_lang ," .
				"nns_producer," .
				"nns_director," .
				"nns_screenwriter ," .
				"nns_actor," .
				"nns_play_role ," .
				"nns_vod_part," .//部数
				"nns_all_index," .//片长
				"nns_view_len," .
				"nns_copyright_date," .
				"nns_copyright_range," .
				"nns_summary,".
				"nns_check,".
				"nns_modify_time," .
				"nns_create_time) " .
				"values ";
		//$nns_org_id = 'c2daa63f7258af654ab0cce05d0f3233';
		//$depot_id = 'c385235885fae27f195385894bd82ed8';
		$nns_create_time = date('Y-m-d H:i:s');
        $fail_arr = array();
        $sql_value = '';
        foreach($dataset['cells'] as $key=>$data){
        	//
        	if($key <1 && $data[0]=='片名') {//第一行是 录入提示导航，从Excel第二行起是媒体数据部分
        		continue;
        	}
            $fail_item = array();
            $fail_item['index'] = $key;//行号
            $fail_item['data'] = $data;
        	if(empty($data[0])){

        		$fail_item['error'] = '没有填写媒体名称';

        		$fail_arr[] = $fail_item;
        		continue;
        	}
        	$fail_item['name'] = $data[0];

        	$category_name = null;

            $category_name_arr = array();
            /*
            $category_name_1 =null;
            $category_name_2 =null;
            $category_name_3 =null;
            */
        	if(!empty($data[3])){//一级分类
        		//$category_name_1 = trim($data[D]);
        		$category_name_arr[0]=  trim($data[3]);

	        	if(!empty($data[4])){//二级分类
	        		//$category_name_2 = trim($data[E]);
	        		$category_name_arr[1]=  trim($data[4]);

		        	if(!empty($data[5])){//三级分类
		        		//$category_name_3 = trim($data[F]);
		        		$category_name_arr[2]=  trim($data[5]);
		        	}
	        	}

        	}else{
        	 	$fail_item['error'] = '没有找到一级分类';
        	 	$fail_arr[] = $fail_item;
        	 	continue;
        	}
	        if(empty($data[12])){
                 $fail_item['error'] = '没有输入集数';
                 $fail_arr[] = $fail_item;
             	 continue;
	        }
        	$depot_detail_id = null;
        	$xml_str = $this->get_category_tree($depot_id);
			$dom = new DOMDocument('1.0', 'utf-8');
			$dom->loadXML($xml_str);
			$category = $dom->getElementsByTagName('category');
            $depot_detail_id=0;
            $not_found_category_name = '';
            foreach($category_name_arr as $category_name){
                 $depot_detail_id = $this->_get_category_detail_id($category,$category_name,$depot_detail_id);
                 if($depot_detail_id == null){
                 	$not_found_category_name = $category_name;
	        	 	break;
                 }
            }

             if(empty($depot_detail_id))
             {
                 $fail_item['error'] = '没有找到分类'.$not_found_category_name;
                 $fail_arr[] = $fail_item;
             	 continue;
             }
        	$nns_summary = $data[18];

            $nns_view_len = $data[17]*60;


            $pinyin=nns_controls_pinyin_class::get_pinyin_letter($data[0]);
     		//生成GUID
			$guid = new Guid ();
			$id = $guid->toString ();

			$data[21] = preg_replace('~\r[\n]?~', "\n", $data[21]);
			$summary_arr =   explode("\n",$data[21]);

            //分（片）集信息
        	$vod_index = array(
        	    'nns_name'      => $data[0],
        	    'nns_vod_id'    => $id,
        	    //'nns_all_index' => '',
        	    'nns_view_len'  => $nns_view_len,
        	    'nns_summary'   => $summary_arr,
        	);
        	$copyright_time = date('Y-m-d H:i:s',strtotime($data[18]));
        	//判断是连续剧还是电影
        	$nns_view_type =0;
        	if(intval($data[16]) >1) {
        		$nns_view_type =1;
        	}

        	$sql_value .= "('".$id."','".
        	$depot_id."','".
        	$depot_detail_id."'," .
			"$nns_view_type," .
			"1,'".  //Excel导入标识
			$pinyin."',',1,',0,'".$nns_org_type."','".$nns_org_id."','".
        	$data[0]."','".
        	$data[1]."','".
        	$data[2]."','".
        	$data[7]."','".
        	$data[8]."','".
        	$data[9]."','".
        	$data[10]."','".
        	$data[11]."','".
        	$data[12]."','".
        	$data[13]."','".
        	$data[14]."','".
        	$data[15]."','".//部数
        	$data[16]."','".//集数
        	$nns_view_len."','".//片长（分钟）
        	$copyright_time."','".
        	$data[19]."','".
        	$data[21]."',".
        	"0," .
        	"'".$nns_create_time."','".
        	$nns_create_time."'),";


	        $vod_index['nns_all_index'] = $data[16];


            //保存分集信息
        	$this->save_vod_index($vod_index);


        }
        $sql_value = rtrim($sql_value,',');
        if($sql_value){
	        $sql .=$sql_value;
	        $result=$this->db_obj->nns_db_execute($sql);

	        $this->log->write($sql ."\n".var_export($result,true));
        }


        if(count($fail_arr)>0){
        	$this->log->write('失败数据：'.var_export($fail_arr,true) );
            return $fail_arr;
        }
        return true;
	}
	private function save_vod_index($vod_index){
		$sql = "insert into nns_vod_index(nns_id,nns_name ,nns_vod_id,nns_index,nns_time_len,nns_summary,nns_create_time) values ";
		for($index=0; $index < $vod_index['nns_all_index'];$index++){
		//生成GUID
		$guid = new Guid ();
		$id = $guid->toString ();
		$sql .= " ('".$id . "','" .
				$vod_index['nns_name']."','" .
				$vod_index['nns_vod_id']."','" .
				$index."','" .
				ceil($vod_index['nns_view_len']/$vod_index['nns_all_index'])."','" .
				$vod_index['nns_summary'][$index]."','" .
				date("Y-m-d H:i:s")."'),";
		}
		$sql = rtrim($sql,',');

       $this->db_obj->nns_db_execute($sql);

	}
	public function get_category_tree($depot_id){
		$sql = "select nns_category from nns_depot where nns_id='$depot_id' limit 1";

		$result = $this->db_obj->nns_db_query($sql);

		return isset($result['data'])?$result['data'][0]['nns_category']:null;
	}
	function _get_category_detail_id($category, $category_name, $depot_detail_id = null){
		if($depot_detail_id === null) return null;
		 if($depot_detail_id===0){
			 foreach($category as $item){
		 		if ($item->getAttribute("name")==$category_name && $item->getAttribute("parent")==0)
		 		{
		 			return $item->getAttribute("id");
		 		}
		 	}
		 }
		 else if($category_name && $depot_detail_id){
		 	foreach($category as $item){
		 		if ($item->getAttribute("parent")==$depot_detail_id && $item->getAttribute("name")==$category_name)
		 		{
		 			return $item->getAttribute("id");
		 		}

		 	}
		 }
		 return null;
	}
}
